const db = require('./db').clien;
const multer = require('multer')
const formidable = require('formidable');
const fs = require('fs');
const crypto = require('crypto');
const express = require('express');
const cookieParser = require('cookie-parser');//?cookie解析中间件
const bodyParser = require('body-parser');//?body解析中间件
const { json } = require('express');
const sd = require('silly-datetime');//?生成时间格式
const app = express();//?生成路由实例
app.use(cookieParser());//?挂载cookie解析器
app.use(bodyParser.urlencoded({ extended: false }));//?挂在body解析器
db.connect(function (err) {//?连接数据库
    if (err) console.error('连接错误：' + err);
    else console.log("数据库连接成功");
})

var re_Changed = /\(Rows matched: \d  Changed: (\d)  Warnings/
var re_Changed1 = /\(Rows matched: (\d)  Changed: \d  Warnings/

//?Cookie查询
const View_Cookie = function (request, calka) {
    db.query('select * from login where UserCookie=\'' + request.cookies.DOM_Cookie + '\'', function (err, data) {
        calka(err, data)
    })
}

var upload = multer();
//?保存用户图片
app.post('/picture', upload.single('file'), function (request, response) {
    // console.log(request.file);
    let { buffer, mimetype } = request.file;//?获取文件内容
    View_Cookie(request, function (err, data) {
        console.log(data);
        db.query('select * from user where UserID=' + data[0]['UserID'], function (err, data_) {
            let fileType = mimetype.split('/')[1];//?文件类型
            let fileName = data[0]['UserID'] + '.' + fileType;//?文件名
            fs.writeFile(`./picture/${fileName}`, buffer, (err) => {
                if (err) {
                    response.send({ err: 1, msg: "上传失败" })
                } else {
                    db.query('update user set Portrait=\'' + fileName + '\' where UserID=' + data[0]['UserID'], function (err, data) {
                        if (err) console.error(err);
                        response.send({ err: 0, msg: "上传成功" })
                    })
                }
            })
        })
    })
})

//?注册</registered>
app.post('/regisstered', function (request, response) {
    console.log('select * from user where UserID=' + request.body.UserID);
    var res = /^[0-9]+$/g.test(request.body.UserID)
    if (res) {
        db.query('select * from user where UserID=' + (request.body.UserID), function (err, data) {
            if (err) console.error(err);
            if (data[0] == null) {
                db.query(
                    'insert user(UserID,UserPassword,UserName) values(' + request.body.UserID + ',\'' + request.body.UserPassword + '\',\'' + request.body.UserName + '\')',
                    function (err, data_) {
                        if (err) {
                            console.error(err);
                            response.send({ "code": -1, "msg": "error" })
                        }
                        else {
                            console.log(data_);
                            const md5 = crypto.createHash('md5');//?生成md5实例（一次性）
                            let time__ = new Date().getTime();//?时间戳
                            const cookie = md5.update(String(parseInt(time__ * 3000))).digest('hex');//?md5加密
                            db.query('update login set UserCookie=\'' + cookie + '\' where UserID=' + request.body.UserID, function (err, data) {
                                response.cookie('DOM_Cookie', cookie, { maxAge: 60 * 60000 });
                                response.send({ "code": 0, "msg": "注册成功" })
                            })

                        }
                    })
            } else response.send({ "code": 1, "msg": "账号已注册" })


        })
    }
    else response.send({ "code": -1, "msg": "账号只能为数字" })

})

//?login，登录接口</login>
app.post('/login', function (request, response) {
    if (request.body.UserPassword != null && request.body.UserID != null) {
        // console.log(request.body.UserID);
        db.query('select UserPassword from user where UserID=?', [request.body.UserID], function (err, data) {
            if (err) {
                console.error(err);
                response.send({ "code": -1, "msg": "error" })
            }
            else {
                console.log(data);
                if (data[0]) {
                    if (data[0]['UserPassword'] == request.body.UserPassword) {
                        const md5 = crypto.createHash('md5');//?生成md5实例（一次性）
                        let time__ = new Date().getTime();//?时间戳
                        const cookie = md5.update(String(parseInt(time__ * 3000))).digest('hex');//?md5加密
                        db.query('update login set UserCookie=\'' + cookie + '\' where UserID=' + request.body.UserID, function (err, data) {
                            response.cookie('DOM_Cookie', cookie, { maxAge: 60 * 60 * 1000 });
                            response.send({ "code": 0, "msg": "登录成功" })
                        })
                    }
                    else response.send({ "code": -1, "msg": "密码错误" })
                } else response.send({ "code": -1, "msg": "账号不存在" })
            }
        })
    } else response.send({ "code": -1, "msg": "error" })
})

//?退出登录
app.post('/exit', function (request, response) {
    response.clearCookie('DOM_Cookie')
    response.end()
})

//? 浏览页响应
app.get('/', function (request, response) {
    View_Cookie(request, function (err, data) {
        response.cookie('DOM_Cookie', request.cookies.DOM_Cookie, { maxAge: 60 * 60 * 1000 });

        fs.readFile('html/recipe.html', function (err, data_) {
            // console.log(data);
            if (data[0]) {
                let html = data_.toString().replace(`<li class="nav-item"><a id="login" class="nav-link" href="./login">登录</a></li>`, `<li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"
                    aria-expanded="false">
                    我的
                </a>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="./myselfs_part">个人中心</a></li>
                    <li><a class="dropdown-item" href="./myrelease" id="myrelease">我的发布</a></li>
                    <li><a class="dropdown-item" href="./html/insert" id="wantrelease">我要发布</a></li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li><a class="dropdown-item" href="#" id="Exit">退出登录</a></li>
                </ul>
            </li>`)
                response.send(html)
            }
            else response.send(data_.toString())
        })
    })

})

//? 菜品添加页面
app.get('/insert', function (request, response) {
    response.cookie('DOM_Cookie', request.cookies.DOM_Cookie, { maxAge: 60 * 60 * 1000 });
    fs.readFile('html/insert.html', function (err, data) {
        response.send(data.toString())
    })
})

//?个人中心页面
app.get('/myselfs_part', function (request, response) {
    response.cookie('DOM_Cookie', request.cookies.DOM_Cookie, { maxAge: 60 * 60 * 1000 });
    fs.readFile('html/myselfs_part.html', function (err, data) {
        response.send(data.toString())
    })
})

//?个人中心页面
app.get('/myrelease', function (request, response) {
    response.cookie('DOM_Cookie', request.cookies.DOM_Cookie, { maxAge: 60 * 60 * 1000 });

    fs.readFile('html/myrelease.html', function (err, data) {
        response.send(data.toString())
    })
})

//?菜品详情页
app.get('/details/:FoodID', function (request, response) {
    response.cookie('DOM_Cookie', request.cookies.DOM_Cookie, { maxAge: 60 * 60 * 1000 });

    View_Cookie(request, function (err, data) {
        if (data[0]) {
            db.query('select * from recipe where FoodID=\'' + request.params.FoodID + '\' and UserID=' + data[0].UserID, function (err, data1) {
                if (data1[0]) {
                    fs.readFile('html/details.html', function (err, data) {
                        response.send(data.toString().replace('<input type="" id="FoodID" style="display: none;" data-FoodID="">', '<input type="" id="FoodID" style="display: none;" data-FoodID="' + request.params.FoodID + '">'))
                    })
                } else {
                    fs.readFile('html/details.html', function (err, data) {
                        response.send(data.toString().replace('<li class="nav-item"><a class="nav-link" href="#">修改</a></li>', '').replace('<input type="" id="FoodID" style="display: none;" data-FoodID="">', '<input type="" id="FoodID" style="display: none;" data-FoodID="' + request.params.FoodID + '">'))
                    })
                }

            })
        } else {
            fs.readFile('html/details.html', function (err, data) {
                response.send(data.toString().replace('<li class="nav-item"><a class="nav-link" href="#">修改</a></li>', '').replace('<input type="" id="FoodID" style="display: none;" data-FoodID="">', '<input type="" id="FoodID" style="display: none;" data-FoodID="' + request.params.FoodID + '">'))
            })
        }
    })
})

//?登录页响应
app.get('/login', function (request, response) {
    fs.readFile('html/login.html', function (err, data) {
        response.send(data.toString())
    })
})

//?页面请求
app.get('/html/:op', function (request, response) {
    if (request.params.op == 'login') {
        response.redirect('/login')
    }
    else if (request.params.op == 'insert') {
        if (request.cookies.DOM_Cookie)
            response.redirect('/insert')
    } else if (request.params.op == 'recipe') response.redirect('/')
    else if (request.params.op == 'myselfs_part') response.redirect('/myselfs_part')
    else if (request.params.op == 'details') response.redirect('/details')
    else response.end()
})

//?js响应
app.get('/js/jquery', function (request, response) {
    fs.readFile('js/jquery-3.4.1.min.js', function (err, data) {
        response.send(data.toString())
    })
})

//?图片响应
app.get('/img/:path', function (request, response) {
    fs.readFile('img/' + request.params.path, function (err, data) {
        response.send(data)
    })
})

//?发布者头像响应
app.get('/Head_p/:UserID', function (request, response) {
    db.query('select Portrait from user where UserID=' + request.params.UserID, function (err, data1) {
        console.log(request.params.UserID, data1);
        if (data1[0]) {
            fs.readFile('./picture/' + data1[0].Portrait, function (err, data2) {
                if (err) {
                    console.error(err);
                    fs.readFile('./picture/default.png', function (err, data) {
                        response.send(data)
                    })
                } else response.send(data2)
            })
        } else fs.readFile('./picture/default.png', function (err, data) {
            response.send(data)

        })

    })
})

//?用户头像响应
app.get('/Head_p', function (request, response) {

    View_Cookie(request, function (err, data) {
        if (data[0]) {
            db.query('select Portrait from user where UserID=' + data[0].UserID, function (err, data1) {
                fs.readFile('./picture/' + data1[0].Portrait, function (err, data2) {
                    if (err) {
                        console.error(err);
                        fs.readFile('./picture/default.png', function (err, data) {
                            response.send(data)
                        })
                    } else response.send(data2)
                })
            })
        } else {
            fs.readFile('./picture/default.png', function (err, data) {
                response.send(data)

            })
        }
    })
})

//?样图响应
app.get('/img/:img', function (request, response) {
    fs.readFile('picture/' + request.params.img, function (err, data) {
        response.send(data)
    })
})

//?个人信息</user>
app.post('/UserData', function (request, response) {
    if (request.body.UserID) {
        db.query('select UserID,UserName,MenuNum,FansNum from user where UserID=' + request.body.UserID, function (err, data) {
            if (err) {
                console.log(err);
                response.send({ "code": -1, "result": 'error' })
            }
            else if (data[0] != null)
                response.send({ "code": 0, "result": data[0] })
            else response.send({ "code": -1, "result": 'error' })
        })
    } else
        View_Cookie(request, function (err, data) {
            if (err) {
                console.log(err);
                response.send({ "code": -1, "result": 'error' })
            } else {
                if (data[0] != null) {
                    db.query('select * from user where UserID=' + data[0]['UserID'], function (err, data) {
                        if (err) {
                            console.log(err);
                            response.send({ "code": -1, "result": 'error' })
                        }
                        else if (data[0] != null)
                            response.send({ "code": 0, "result": data[0] })
                        else response.send({ "code": -1, "result": 'error' })
                    })
                } else response.send({ "code": -1, "result": 'error' })
            }
        })
})

//?信息修改
app.post('/UserName_change', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (data[0]) {
            db.query('update user set UserName=\'' + request.body.UserName + '\'', function (err, data1) {
                if (err) {
                    console.error(err);
                    response.send({ "code": -1, "result": 'error' })
                } else {
                    response.send({ "code": 0, "result": 'OK' })
                }
            })
        } else response.send({ "code": -1, "result": 'error' })
    })
})

//?密码修改
app.post('/change_pas', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (data[0]) {
            db.query('select * from user where UserID=' + data[0].UserID, function (err, data) {
                console.log(request.body.old_pas, data[0].UserPassword);
                if (err) console.error(err);
                if (request.body.old_pas == data[0].UserPassword) {
                    db.query('update user set UserPassword=? where UserID=?', [request.body.new_pas, data[0].UserID], function (err, data1) {
                        response.send({ "code": 0, "result": '修改成功' })
                    })
                } else response.send({ "code": 1, "result": '旧密码错误' })
            })

        } else response.send({ "code": -1, "result": 'error' })
    })
})

//?收藏操作</collection>
app.post('/collection/:op', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (err) {
            console.log(err);
            response.send({ "code": -1, "result": 'error' })
        } else {
            if (data[0])
                switch (request.params.op) {
                    case 'insert':
                        db.query('select count(*) from collection where FoodID=? and UserID=?', [request.body.FoodID, data[0]['UserID']], function (err, data1) {
                            if (err) {
                                console.error(err);
                                response.send({ "code": -1, "data": "error" })
                            } else {
                                if (data1[0]['count(*)'] == 0) {//判断是否已经收藏
                                    db.query('insert collection values(?,?)', [request.body.FoodID, data[0]['UserID']], function (err, data_) {
                                        if (err) response.send({ "code": -1, "data": "error" });
                                        else response.send({ "code": 0, "data": "OK" });
                                    })
                                } else {
                                    response.send({ "code": 0, "data": "已收藏" })
                                }
                            }
                        })

                        break;
                    case 'select':
                        db.query('select FoodID,UserID from collection where UserID=' + data[0]['UserID'], function (err, data_) {
                            if (err) response.send({ "code": -1, "data": "error" });
                            else response.send({ "code": 0, "data": data_ });
                        })
                        break;
                    case 'delete':
                        console.log('delete from collection where FoodID=' + request.body.FoodID + ' and UserID=' + data[0]['UserID'] + ' ');
                        db.query('delete from collection where FoodID=? and UserID=? ', [request.body.FoodID, data[0]['UserID']], function (err, data) {
                            if (err) {
                                response.send({ "code": -1, "data": "error" });
                            } else response.send({ "code": 0, "data": "OK" });

                        })
                        break
                    default:
                        response.send({ "code": -1, "data": "error" });
                        console.log('error');
                }
        }

    })
})

//?菜谱类别</class>
app.post('/class', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (err) {
            console.log(err);
            response.send({ "code": -1, "result": 'error' })
        } else {
            //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
            db.query('select * from class', function (err, data) {
                response.send({ "code": 0, "data": data })
            })
            //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
        }
    })
})

//?获取所有菜谱
app.post("/recipes", function (request, response) {
    if (request.body.FoodName) {
        db.query('select * from recipe where FoodName like \'%' + request.body.FoodName + '%\'', function (err, data) {
            if (err) console.error(err);

            response.send({ "code": 0, "data": data })
        })
    } else if (request.body.FoodID) {
        db.query('select * from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
            if (err) console.error(err);
            if (data[0])
                response.send({ "code": 0, "data": data[0] })
            else
                response.send({ "code": -1, "data": 'error' })

        })
    }
    else {
        db.query('select ClassID,FoodID,FoodName,Samplefigure,Release_time,UserID  from recipe', function (err, data) {
            response.send({ "code": 0, "data": data })
        })
    }

})

//?获取发布菜谱
app.post('/recipese/User', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (data[0]) {
            db.query('select FoodID,Practice,Message,FoodName,Release_time,CollectionNum from recipe where UserID=' + data[0].UserID, function (err, data1) {
                if (err) console.error(err);
                if (data1[0]) {
                    response.send({ "code": 0, "data": data1 })
                }
                else response.send({ "code": 1, "data": '您还未发布菜单' })
            })
        } else {
            response.send({ "code": -1, "data": 'error' })

        }
    })

})

//?菜谱操作</recipe>
app.post('/recipe/:operation', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (err) {
            console.error(err);
            response.send({ "code": -1, "result": 'error' })
        } else {
            //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
            if (data[0]) {
                switch (request.params.operation) {
                    case 'insert':
                        const md5 = crypto.createHash('md5');//?生成md5实例（一次性）
                        let time__ = new Date().getTime();//?时间戳
                        const FoodID = md5.update(String(parseInt(time__ * 3000))).digest('hex');//?md5加密
                        // console.log(FoodID);
                        var updatetimes = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                        console.log(updatetimes);
                        db.query('insert recipe(Release_time,FoodID,FoodName,practice,Formula,UserID,ClassID) values(?,?,?,?,?,?,?)',
                            [
                                updatetimes,
                                FoodID,
                                request.body.FoodName,
                                request.body.practice,
                                request.body.Formula,
                                data[0].UserID,
                                request.body.ClassID,
                            ], function (err, data) {
                                if (err) {
                                    console.error(err);
                                    // console.log(request.body.Formula);
                                    response.send({ "code": -1, "result": 'error' })
                                } else {
                                    console.log(data);
                                    if (data['affectedRows'] == 1)
                                        response.send({ "code": 0, "FoodID": FoodID })
                                    else response.send({ "code": 0, "result": "error" })
                                }
                            })
                        break
                    case 'select':
                        const re = new RegExp(/(\d+)/g)
                        let sql_ = 'select * from recipe where'
                        while (re.lastIndex < request.body.ClassID.length) {
                            sql_ += ' ClassID=' + re.exec(request.body.ClassID)[0] + ' or'//?拼接条件语句
                        }
                        sql_ = sql_.substring(0, sql_.length - 3)//?截取字符串有效部分
                        db.query(sql_, function (err, data) {
                            if (err) {
                                console.error(err);
                                response.send({ "code": -1, "result": 'error' })
                            } else {
                                response.send(data[0])
                            }
                        })
                        break
                    case 'update':
                        db.query('update recipe set FoodName=?,Samplefigure=?,Formula=?,ClickNum=?,Message=?,ClassID=? where FoodID=?',
                            [
                                updatetimes,
                                request.body.FoodName,
                                request.body.Samplefigure,
                                request.body.Formula,
                                request.body.ClickNum,
                                request.body.Message,
                                request.body.ClassID,
                                request.body.FoodID,
                            ]
                            , function (err, data) {
                                if (err) {
                                    console.error(err);
                                    response.send({ "code": -1, "result": 'error' })
                                } else {
                                    response.send({ "code": 0, "result": "success" })
                                }
                            })
                        break
                    case 'delete':
                        db.query('delete from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                            if (err) {
                                console.error(err);
                                response.send({ "code": -1, "result": 'error' })
                            } else {
                                console.log(data);
                                response.send({ "code": 0, "result": "success" })
                            }
                        })
                        break
                    default:
                        response.send({ "code": -1, "result": 'error' })
                        console.log('error');
                }
                //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
            } else {
                response.send({ "code": -1, "result": 'error' })
                console.log('error');
            }

        }
    })
})

//?菜品图片接收
app.post('/addimg', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (data[0]) {
            // ?创建formidable表单解析对象
            const form = new formidable.IncomingForm();
            //?更改文件地址
            form.uploadDir = __dirname + '/img'
            //?解析用户传递过来的Formdata对象
            form.parse(request, (err, fields, files) => {
                // ?修改文件名

                fs.rename(files.file.filepath, __dirname + '/img/' + fields.FoodID + '.' + files.file.mimetype.split('/')[1], function () {
                    db.query("update recipe  set  Samplefigure='./img/" + fields.FoodID + '.' + files.file.mimetype.split('/')[1] + '\'  where FoodID=\'' + fields.FoodID + '\'', function (err, data) {
                        if (err) console.error(err);
                        response.send({ "code": 0, "result": 'succese' })
                    })
                })

            });



        } else response.send({ "code": -1, "result": 'error' })
    })
})

//?留言</message>
app.post('/message/:way', function (request, response) {
    if (request.params.way == 'select') {
        db.query('select Message from recipe where FoodID=?', [request.body.FoodID], function (err, data) {
            if (err) {
                response.send({ "code": -1, "result": 'error' })
            } else {
                response.send({ "code": 0, "data": data[0]['Message'] })
            }
        })
    } else
        View_Cookie(request, function (err, data) {
            if (data[0]) {
                let userid_data = data[0].UserID
                if (err) {
                    console.log(err);
                    response.send({ "code": -1, "result": 'error' })
                } else {
                    //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                    let message_data = {
                        userid: request.body.userid,
                        username: request.body.username,
                        msg: request.body.message,
                        tiem_: request.body.tiem_
                    }
                    switch (request.params.way) {
                        case 'select':
                            db.query('select Message from recipe where FoodID=?', [request.body.FoodID], function (err, data) {
                                if (err) {
                                    console.log(err);
                                    response.send({ "code": -1, "result": 'error' })
                                } else {
                                    response.send({ "code": 0, "data": data[0]['Message'] })
                                }
                            })
                            break
                        case 'insert_update':
                            console.log('select Message from recipe where FoodID=\'' + request.body.FoodID + '\'');
                            db.query('select Message from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                                console.log(data[0].Message);
                                let old_message_data = data[0].Message
                                old_message_data = JSON.parse(old_message_data)//?字符串转对象
                                let time_ = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');//?时间
                                db.query('select UserName from user where UserID=' + userid_data, function (err, data2) {
                                    old_message_data[userid_data] =
                                    {
                                        "userid": userid_data,
                                        "username": data2[0].UserName,
                                        "msg": request.body.message,
                                        "time_": time_
                                    }//?添加字段
                                    let sql_str = JSON.stringify(old_message_data)//?对象转字符串
                                    db.query('update recipe set Message =\'' + sql_str + '\' where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                                        if (err) {
                                            console.log(err);
                                            response.send({ "code": -1, "result": 'error' })
                                        } else {
                                            console.log(data);
                                            response.send({ "code": 0, "data": "success" })
                                        }
                                    })
                                })

                            })
                            break
                        case 'delete':
                            db.query('select Message from recipe where FoodID=?', [request.body.FoodID], function (err, data) {
                                let old_message_data = data[0]['Message']
                                old_message_data = JSON.parse(old_message_data)//?字符串转对象
                                delete old_message_data[request.body.userid]//?添加字段
                                let sql_str = JSON.stringify(old_message_data)//?对象转字符串
                                db.query('update recipe set Message =\'' + sql_str + '\' where FoodID=' + request.body.FoodID, function (err, data) {
                                    if (err) {
                                        console.log(err);
                                        response.send({ "code": -1, "result": 'error' })
                                    } else {
                                        console.log(data);
                                        response.send({ "code": 0, "data": "success" })
                                    }
                                })
                            })
                            break
                        default:
                            response.send({ "code": -1, "result": 'error' })
                            console.log('error');
                    }
                    //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                }
            } else
                response.send({ "code": -1, "result": 'error' })
        })
})


app.listen(52273, function () {
    console.log('服务启动');
})